package com.lagou.java.handler;

import com.lagou.java.NettyServer;
import com.lagou.java.NettyServerBootstrap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class NettyEndPointHandler {

    private static final String host = "127.0.0.1";

//    ZkBoostrap<UserServiceHandler> zkBoostrap = new ZkBoostrap<>();

    // 在端口 port, 添加服务节点
    @GetMapping("/up/{port}")
    public String up(@PathVariable("port") Integer port) {
        String msg = null;
        NettyServerBootstrap.ServerData serverData = NettyServerBootstrap.servers.get(port);
        if ( serverData  == null) {
            NettyServer.startServer(host, port, NettyServerBootstrap.servers);
            msg = "服务在端口：" + port + " 启动成功！";
        } else if (serverData.getChannelFuture().channel().isActive()) {
            msg = "服务已经在在端口：" + port + "端口上运行";
        } else {
            NettyServerBootstrap.servers.remove(port);
            NettyServer.startServer(host, port, NettyServerBootstrap.servers);
            msg = "端口：" + port + "上运行的原服务已经下线, 已经在该端口启动新服务";
        }
        return msg ;
    }

    // 在端口 port, 删除服务节点
    @GetMapping("/down/{port}")
    public String down(@PathVariable("port") Integer port) {
        String msg = null;
        NettyServerBootstrap.ServerData serverData = NettyServerBootstrap.servers.get(port);
        if ( serverData  == null) {
            msg = "端口：" + port + " 没有服务运行！";
        } else if (serverData.getChannelFuture().channel().isActive()) {
            serverData.getChannelFuture().channel().close();
            msg = "服务已经在在端口：" + port + "端口上停止运行";
        } else {
            NettyServerBootstrap.servers.remove(port);
            msg = "端口：" + port + "上运行的原服务已经下线";
        }
        return msg;
    }
}
